/* 
 * 路由
 *  1.模式：
 *    路由的模式有两种：Hash模式、History模式
 *  2.模式的选择：
 *    通常情况下，路由模式选择Hash，因为History模式在页面刷新时会出现404，在服务端也需要进行一些配置。但Hash在地址栏会出现“/#”。
 */
import { createRouter, createWebHashHistory, createWebHistory } from "vue-router";
import axios from "@/api";
import store from "../store";
import { toRaw } from "@vue/reactivity";

//路由中，名字和路径是唯一的
const routes = [
  //“/” 重定向至首页
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login/index.vue')
  },
  {
    path: '/:pathMatch(.*)',
    name: 'notfound',
    component: () => import('../views/notfound.vue')
  },
  {
    path: '/home',
    name: 'home',
    meta: { title: '' },
    redirect: '/index',
    component: () => import('../views/home/index.vue'),
    children: [
      {
        path: '/index', //首页
        name: 'index',
        meta: { title: '控制台' },
        component: () => import('../views/home/index/index.vue'),
      }
    ]
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

const settingRouter = async () => {
  let routeData = [];
  let s = store().accountInfo;
  let { data } = await axios.get(`Menu/${s.userId}`);
  let { data: d, success, message } = data;

  if (success) {
    routeData = d;

    store().iniMenu(d);
  } else {
    routeData = [];
  }

  //组装路由数据
  const modules = import.meta.glob('../views/home/*/info/*.vue');

  var initRouter = (routeList) => {
    var returnRouteArray = [];
    routeList.forEach(item => {
      let obj = {
        path: item.webUrl, //菜单详情
        name: item.routeName,
        meta: {
          id: item.id,
          title: item.menuText,
          keepAlive: true
        },
        component: modules[item.vueFilePath],
        children: []
      }

      //判断子级
      if (item.childMenus && item.childMenus.length > 0) {
        obj.children = initRouter(item.childMenus);

        returnRouteArray.push(obj);
      } else {
        returnRouteArray.push(obj);
      }
    });

    return returnRouteArray;
  }

  let treeRouteList = initRouter(routeData);
  treeRouteList.forEach(element => {
    router.addRoute('home', element);
  });
}

router.beforeEach(async (to, from, next) => {
  if (to.path != '/login') {
    await settingRouter();
  }

  if (store().$state.accessToken == "" || !store().$state.accessToken) {
    if (to.path != "/login") {
      next("/login");
      return;
    }
  }

  //判断 to 对象是否为空
  if (to.name === "notfound") {
    if (router.getRoutes().find(p => p.path === to.path)) {
      next(to.path);
      return;
    }
  }

  if (!to.name) {
    //如果为空，则向next()中传值，以重新执行router.beforeEach
    if (router.getRoutes().find(p => p.path === to.path)) {
      next(to.path);
      return;
    }
  } else {
    //如果不为空则退出router.beforeEach
    next();
  }
})

export default router